package snowflake

import (
	"database/sql/driver"
	"errors"
	"fmt"
	"github.com/bwmarrin/snowflake"
	"strconv"
	"strings"
)

var node, _ = snowflake.NewNode(1)

// Generate 生成 snowflake
func Generate() SFID {
	id := node.Generate()
	return SFID(id.Int64())
}

type SFID int64

func (s SFID) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf("\"%d\"", int64(s))), nil
}
func (s *SFID) UnmarshalJSON(b []byte) error {
	str := strings.Trim(string(b), "\"")
	data, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		return err
	}
	*s = SFID(data)
	return nil
}

// 实现 sql.Scanner 接口，Scan 将 value 扫描至 Jsonb
func (s *SFID) Scan(value interface{}) error {
	data, ok := value.(int64)
	if !ok {
		return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
	}

	*s = SFID(data)
	return nil
}

// 实现 driver.Valuer 接口，Value 返回 json value
func (s SFID) Value() (driver.Value, error) {
	return int64(s), nil
}
